<?php
namespace app\common\logic;

use think\Db;
use Session;
use think\Validate;

class AdminLogic
{
    public function login($input)
    {
        $msg = [
            'username.require' => '登录名不能为空',
            'userpwd.require' => '登录密码不能为空'
        ];
        $validate = new Validate([
            'username' => 'require',
            'userpwd' => 'require'
        ], $msg);

        if (!$validate->check($input)) {
            return ['code'=> 0, 'msg'=>$validate->getError()];
        }

       // Saas::instance()->ssoAdmin($username, $password);

        $condition['a.user_name'] = $input['username'];
        $admin = Db::name('admin_user')->alias('a')->join('__ADMIN_ROLE__ ar', 'a.role_id=ar.role_id')->where($condition)->find();
        if (!$admin) {
            return ['code'=>0, 'msg'=>'登录用户不存在'];
        }
        if (!password_compare($admin['password'], $input['userpwd'], $admin['ec_salt'])) {
            return ['code' => 0, 'msg' => '管理员密码不正确'];
        }

        $this->handleLogin($admin, $admin['act_list']);

        $url = session('from_url') ? session('from_url') : url('Admin/Index/index');
        return ['code' => 1, 'url' => $url, 'msg'=> '登录成功'];
    }

    public function handleLogin($admin, $actList)
    {
        
        Db('admin_user')->where('admin_id', $admin['admin_id'])->update([
            'last_login' => time(),
            'last_ip' => request()->ip()
        ]);

        $this->sessionRoleRights($admin, $actList);

        session::set('admin_id', $admin['admin_id']);
        session::set('last_login_time', $admin['last_login']);
        session::set('last_login_ip', $admin['last_ip']);

        adminLog('后台登录');
    }

    public function sessionRoleRights($admin, $actList)
    {
       // if (Saas::instance()->isNormalUser()) {
       //     $roleRights = Saas::instance()->getRoleRights($actList);
       // } else {
       //     $roleRights = $actList;
       // }

        session('act_list', $actList);
    }

    public function logout()
    {

        session_unset();

        session_destroy();
        Session::clear();
 
    }
}






